<?php
define('CACHE_FILE',1);
define('CACHE_SHM',2);
define('CACHE_METHOD_RETURN',1);
define('CACHE_METHOD_STDOUT',2);


function cache_hit($name)
{
	//统计，日志,etc;
}

function dao_file_cache_read($name,&$buffer,$timeout,$method,&$msg=NULL)
{
	//从文件读出缓冲
	$filename = $name;
	if(!file_exists($filename))
	{
		$msg = "cache file [$filename] not exist";
		return -1;
	}
	$fmtime = filemtime($filename);
	$live_time = time()-$fmtime;
	DAO_Log::debug("cache file [$filename] last write: ".date('H:i:s').",live time $live_time");
	if($live_time>$timeout&&$timeout>0)
	{
		//超时
		$msg = "file cache [$name] is timeout";
		return -2;
	}
	//cache hit
	cache_hit($name);
	DAO_Log::debug("read cache method=$method");
	switch ($method)
	{
		case CACHE_METHOD_RETURN://返回字符串
		{
			$buffer=file_get_contents($filename);
			break;
		}
		case CACHE_METHOD_STDOUT: //直接读到输出缓冲
		{
			DAO_Log::debug( "read file [$filename] to output\r\n");
			readfile($filename);
			break;
		}
		default:
		{
			break;
		}
	}
	return 0;
}

function dao_file_cache_write($name,&$buffer,&$msg=NULL)
{
	$filename = $name;
	//写缓冲文件
	DAO_Log::debug("write to [$filename]: ".strlen($buffer)."bytes \r\n");
	file_put_contents($filename,$buffer);
}

/*读取cache
in]名字
in]方式 :1文件，2shm 3memcache
in]引用的缓冲
in]超时
in]读取到之后如何处理 0: 返回,1:echo出来
返回：0成功
-1没有文件或错误
-2超时
*/
function dao_cache_read($name,&$buffer,$timeout,$method,&$msg,$mode=1)
{
	switch($mode)
	{
		case CACHE_FILE:
		{
			return dao_file_cache_read($name,$buffer,$timeout,$method,$msg);
			break;
		}

	}
}

function dao_cache_write($name,&$buffer,&$msg,$mode=1)
{

	switch($mode)
	{
		case CACHE_FILE:
		{
			return dao_file_cache_write($name,$buffer,$timeout,$method,$msg);
			break;
		}
			

	}
}

//------------------------------------------------------------------------
if(false)
{
	$name = 'cachefile';
	if(dao_file_cache_read($name,$buffer,5,1,$msg)<0)
	{
		echo "read cache : $msg\r\n";
		dao_file_cache_write($name,date('Y-m-d H:i:s'),$msg);
	}
	echo "\r\n";
}
?>